// pages/storeMain/shoreMain.js
import {
  shopCarAdd,
  getUserShopCar,
  changeShopNum,
  clearShop
} from '../../http/api model/shopCar'
const $ = wx.cloud.database().command.aggregate;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    filterShopList:[],
    isloading:true,
    ID: undefined,
    km:0,
    currenIndex: 0,
    foodFenlei: [],
    foodList: [],
    show: false,
    showShopDetail: false,
    selectFenlei: "店长推荐",
    nowShopInfo: {},
    loading: true,
    nowSelectShopInfo: {},
    scrollTop: 20,
    time:false,
    shopCar: {
      totalMoney: 0,
      total: 0,
      shops: []
    },
    bannerData: [
      "../../images/banner-1.webp",
      "../../images/banner-2.webp"
    ],
    selectShopId: undefined
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 开始加载动画
    setTimeout(()=>{
      this.setData({
        time:true
      })
    },500)
    wx.showLoading({
      title: '加载中',
    });
    // 获取路径传递而来的商店id
    this.setData({
      ID: options.ID,
      km:options.km
    })
    // 加载商店信息
    this.getShopInfo()
    // 加载商店的所有商品信息
    this.getShopFoodInfo()
    // 10/16获取购物车数据
    this.getUserShopCarInfoData()
  },
  // 获取店铺信息
  getShopInfo() {
    wx.request({
      url: `http://localhost:5555/shop/checkedMapData?id=${this.data.ID}`,
      method: 'get',
      success: (res) => {
        this.setData({
          nowShopInfo: res.data[0]
        })
        wx.hideLoading()
      },
      fail: () => {}
    })
  },
  // 获取店铺商品信息
  getShopFoodInfo() {
    wx.request({
      url: `http://localhost:5555/shop/shopList?id=${this.data.ID}&openid=${wx.getStorageSync('openID')}`,
      method: 'get',
      success: (res) => {
        this.setData({
          foodList: res.data,
        })
        const fl = res.data.map(i => i.fenlei);
        // // 数组去重
        let setArr = new Set(fl);
        let newArr = Array.from(setArr);
        const { foodList,currenIndex } = this.data
        this.setData({
          foodFenlei: newArr,
          filterShopList:foodList.filter(n=>{
            return n.fenlei == newArr[currenIndex];
          })
        })
        // console.log("商品",this.data.foodList);
        wx.hideLoading()
        // this.changeCount()
        this.setData({
          loading: false,
        });
      },
      fail: () => {}
    })
  },
  changMap() {
    wx.navigateTo({
      url: "/pages/storeInfo/storeInfo"
    })
  },
  // 关闭购物车
  onClose() {
    this.setData({
      show: false
    });
  },
  // 打开购物车
  openShopCar(e) {
    if (this.data?.shopCar?.shops?.length <= 0) return
    if (e.target.id === 'submibt') return
    this.setData({
      show: true
    })
    if (!this.data.shopCar.shops.length) {
      return
    }
  },
  // 增加商品数量
  addShopCount(e) {
    this.setData({
      showShopDetail: true
    })
    const {
      foodList
    } = this.data

    let foodid = e.target.dataset.sid;
    //   // 当前商店的id
    let shopID = this.data.nowShopInfo.id
    let index = foodList.findIndex(i => i._id == foodid);
    //     let id = e.target.dataset.sid;
    foodList[index].num = 0;
    this.setData({
      selectShopId: foodList[index]._id,
      nowSelectShopInfo: foodList[index]
    })
    // 获取当前选中商品的所有多态
    const checkedFood = foodList[index].checkedFood;
    // console.log('ddd', checkedFood);
    // 遍历多态
    for (let item of checkedFood) {
      const nowLabel = Object.values(this.data.nowSelectShopInfo.label).reduce((arr, item) => {
        return arr.concat(item);
      }, []);
      // 当label的序列化字符串相等时候，修改当前商品的数量显示
      if (JSON.stringify(nowLabel) == JSON.stringify(item.label)) {
        console.log("匹配到了");
        foodList[index].num = item.num;
        this.setData({
          nowSelectShopInfo: foodList[index]
        })
        return
      }
    }
    console.log("没有匹配到");

  },
  // 在购物车中,修改购物车商品数量
  changNum(e) {
    const {
      foodid: id,
      num,
      state
    } = e.currentTarget.dataset
    // console.log('点击了', id, num, state);
    changeShopNum({
      id,
      num,
      state
    }).then(res => {
      this.getUserShopCarInfoData()
    })
  },
  // 商品详细页加入购物车
  addSelectShopId(e) {
    const num = e.currentTarget.dataset.num
    wx.showLoading({
      title: '加载中',
    });
    const shopid = this.data.nowShopInfo.id;
    const userid = wx.getStorageSync('openID');
    const {
      nowSelectShopInfo
    } = this.data
    nowSelectShopInfo.num += num;
    this.setData({
      nowSelectShopInfo
    })
    shopCarAdd({
      ...nowSelectShopInfo,
      num,
      userid,
    }).then(res => {
      // 更新购物车信息
      this.getUserShopCarInfoData()
      this.getShopFoodInfo()
      wx.hideLoading()
    })
  },

  // 获取购物车信息
  getUserShopCarInfoData() {
    const userid = wx.getStorageSync('openID');
    const shopid = this.data.ID;
    getUserShopCar({
      userid,
      shopid
    }).then(res => {
      this.setData({
        shopCar: res
      })
    })
  },
  // 点击nav切换食品
  changeCurrenIndex(e) {
    console.log();
    const { kind } = e.target.dataset;
    this.setData({
      currenIndex: e.target.dataset.index
    })
    var query = wx.createSelectorQuery();
    const filterShopList=this.data.foodList.filter(n=>n.fenlei==kind)
    this.setData({
      selectFenlei: kind,
      filterShopList
    })
  },
  // 获得食品分类
  getFoodFenlei() {
    wx.cloud.database().collection('food').aggregate()
      .group({
        _id: '$fenlei'
      })
      .end()
      .then(res => {
        this.setData({
          foodFenlei: res.list
        })
        this.getFoodList();

      })
  },
  // 清空购物车
  clearShopList(e) {
    const {
      ID: shopid
    } = this.data;
    const userid = wx.getStorageSync('openID');
    clearShop({
      shopid,
      userid
    }).then(res => {
      this.getUserShopCarInfoData()
      this.getShopFoodInfo()
      this.setData({
        show: false,
      })
    })

  },
  // 去结算页面
  goToPlaceOrder(e) {
    console.log(this.data.shopCar.shops,'当前数据');
    console.log('当前数据',this.data.shopCar);
    const { nowShopInfo,shopCar } = this.data
    nowShopInfo.selectShopCar = shopCar.shops;
    wx.setStorageSync('shopCarINFO',nowShopInfo)
    if (!wx.getStorageSync('openID')) {
      console.log("----------没有登录哦！--------");
      setTimeout(() => {
        wx.redirectTo({
          url: "/pages/me/me"
        }, 0)
      })
      return
    }
    console.log('获取点击', e.target);
    let id = e.target.dataset.shoid
    wx.navigateTo({
      url: `/pages/placeOrder/placeOrder?shopId=${id}`
    })
  },
  // 改变选中的标签
  changeCheckLabel(e) {
    let labelid = e.target.dataset.item.id;
    let labelType = e.target.dataset.item.type
    const arr = this.data.nowSelectShopInfo.label;
    console.log('log', arr, arr[labelType]);
    for (let item of arr[labelType]) {
      item.ischeck = 0;
    }
    for (let item of arr[labelType]) {
      if (item.id == labelid) item.ischeck = 1;
    }

    this.setData({
      [`nowSelectShopInfo.label.${labelType}`]: arr[labelType]
    })
    const {
      foodList
    } = this.data;
    const {
      nowSelectShopInfo
    } = this.data;
    const index = foodList.findIndex(n => n._id == nowSelectShopInfo._id)
    // 获取当前选中商品的所有多态
    const checkedFood = foodList[index].checkedFood;
    console.log('ddd', checkedFood);
    // 遍历多态
    for (let item of checkedFood) {
      const nowLabel = Object.values(this.data.nowSelectShopInfo.label).reduce((arr, item) => {
        return arr.concat(item);
      }, []);
      // 当label的序列化字符串相等时候，修改当前商品的数量显示
      if (JSON.stringify(nowLabel) == JSON.stringify(item.label)) {
        console.log("匹配到了");
        foodList[index].num = item.num;
        this.setData({
          nowSelectShopInfo: foodList[index]
        })
        return
      }
    }
    nowSelectShopInfo.num = 0
    this.setData({
      nowSelectShopInfo
    })
    console.log(e.target.dataset.nowshop._id);
  }
})